const { app, BrowserWindow, ipcMain, screen, Menu } = require('electron');
const path = require('path');

let mainWindow;
let overlaySettings = {
    opacity: 0.9,
    width: 800,
    height: 600,
    x: 100,
    y: 100,
    alwaysOnTop: true
};

function createWindow() {
    // 禁用菜单栏
    Menu.setApplicationMenu(null);
    
    // 获取屏幕信息
    const primaryDisplay = screen.getPrimaryDisplay();
    const { width, height } = primaryDisplay.workAreaSize;

    // 确保窗口在屏幕范围内
    const windowX = Math.max(0, Math.min(overlaySettings.x, width - overlaySettings.width));
    const windowY = Math.max(0, Math.min(overlaySettings.y, height - overlaySettings.height));

    // 创建悬浮窗
    mainWindow = new BrowserWindow({
        width: overlaySettings.width,
        height: overlaySettings.height,
        x: windowX,
        y: windowY,
        frame: false, // 无边框
        transparent: true, // 透明背景
        alwaysOnTop: overlaySettings.alwaysOnTop, // 置顶
        skipTaskbar: false, // 在任务栏显示，方便调试
        resizable: true, // 可调整大小
        show: false, // 先不显示，等加载完成再显示
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            enableRemoteModule: false,
            webSecurity: false,
            backgroundThrottling: false // 防止后台节流
        }
    });

    // 页面加载完成后显示窗口
    mainWindow.once('ready-to-show', () => {
        console.log('Window ready to show');
        
        // 强制显示窗口
        mainWindow.show();
        mainWindow.setOpacity(overlaySettings.opacity);
        
        // 确保窗口在屏幕中央可见
        const bounds = mainWindow.getBounds();
        console.log('Window bounds:', bounds);
        
        // 如果窗口在屏幕外，重新定位到屏幕中央
        const display = screen.getPrimaryDisplay();
        const centerX = Math.round((display.bounds.width - bounds.width) / 2);
        const centerY = Math.round((display.bounds.height - bounds.height) / 2);
        
        if (bounds.x < 0 || bounds.y < 0 || 
            bounds.x > display.bounds.width || bounds.y > display.bounds.height) {
            console.log('Window is outside screen bounds, repositioning to center');
            mainWindow.setPosition(centerX, centerY);
        }
        
        // 确保窗口可见并始终置顶
        mainWindow.focus();
        mainWindow.moveTop();
        mainWindow.setAlwaysOnTop(true, 'screen-saver');
        
        // 强制窗口到前台
        mainWindow.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });
        mainWindow.setFullScreenable(false);
        
        // 添加延迟确保窗口真正显示
        setTimeout(() => {
            mainWindow.focus();
            mainWindow.moveTop();
            console.log('Window final position:', mainWindow.getBounds());
            console.log('Window visible:', mainWindow.isVisible());
            console.log('Window minimized:', mainWindow.isMinimized());
        }, 1000);
        
        // 打开开发者工具（调试模式或显示问题时）
        if (process.argv.includes('--debug') || process.argv.includes('--show')) {
            mainWindow.webContents.openDevTools();
            console.log('Developer tools opened for debugging');
        }
        
        console.log('Floating overlay window displayed and positioned');
    });
    
    // 定期确保窗口置顶（防止被游戏覆盖）
    setInterval(() => {
        if (mainWindow && !mainWindow.isDestroyed() && overlaySettings.alwaysOnTop) {
            mainWindow.setAlwaysOnTop(true, 'screen-saver');
            mainWindow.moveTop();
        }
    }, 3000); // 每3秒检查一次

    // 加载悬浮窗页面
    mainWindow.loadFile('overlay.html').then(() => {
        console.log('HTML file loaded successfully');
    }).catch((error) => {
        console.error('Failed to load HTML file:', error);
    });

    // 调试模式下打开开发者工具
    if (process.argv.includes('--debug') || process.env.NODE_ENV === 'development') {
        mainWindow.webContents.openDevTools();
    }

    // 添加错误处理
    mainWindow.webContents.on('crashed', () => {
        console.error('Window crashed');
    });

    mainWindow.webContents.on('unresponsive', () => {
        console.error('Window unresponsive');
    });
    
    // 当窗口获得焦点时确保置顶
    mainWindow.on('focus', () => {
        if (overlaySettings.alwaysOnTop) {
            mainWindow.setAlwaysOnTop(true, 'screen-saver');
            mainWindow.moveTop();
        }
    });
    
    // 当窗口被点击时确保置顶
    mainWindow.webContents.on('before-input-event', (event, input) => {
        if (input.type === 'mouseDown' && overlaySettings.alwaysOnTop) {
            mainWindow.setAlwaysOnTop(true, 'screen-saver');
            mainWindow.moveTop();
        }
    });

    // 保存窗口位置和大小
    mainWindow.on('moved', () => {
        const [x, y] = mainWindow.getPosition();
        overlaySettings.x = x;
        overlaySettings.y = y;
    });

    mainWindow.on('resized', () => {
        const [width, height] = mainWindow.getSize();
        overlaySettings.width = width;
        overlaySettings.height = height;
    });

    // 窗口关闭时的处理
    mainWindow.on('closed', () => {
        mainWindow = null;
    });
}

// 应用准备就绪时创建窗口
app.whenReady().then(() => {
    console.log('Electron app ready, creating window...');
    createWindow();
}).catch((error) => {
    console.error('Failed to start app:', error);
});

// 当所有窗口都被关闭时退出应用（macOS除外）
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
});

// IPC 通信处理
ipcMain.handle('get-settings', () => {
    return overlaySettings;
});

ipcMain.handle('update-settings', (event, newSettings) => {
    overlaySettings = { ...overlaySettings, ...newSettings };
    
    // 应用设置
    if (mainWindow) {
        if (newSettings.opacity !== undefined) {
            mainWindow.setOpacity(newSettings.opacity);
        }
        
        if (newSettings.width !== undefined || newSettings.height !== undefined) {
            mainWindow.setSize(
                newSettings.width || overlaySettings.width,
                newSettings.height || overlaySettings.height
            );
        }
        
        if (newSettings.x !== undefined || newSettings.y !== undefined) {
            mainWindow.setPosition(
                newSettings.x || overlaySettings.x,
                newSettings.y || overlaySettings.y
            );
        }
        
        if (newSettings.alwaysOnTop !== undefined) {
            if (newSettings.alwaysOnTop) {
                mainWindow.setAlwaysOnTop(true, 'screen-saver');
                mainWindow.moveTop();
            } else {
                mainWindow.setAlwaysOnTop(false);
            }
        }
    }
    
    return overlaySettings;
});

// 点击穿透控制
ipcMain.handle('set-click-through', (event, ignore) => {
    if (mainWindow && !mainWindow.isDestroyed()) {
        try {
            mainWindow.setIgnoreMouseEvents(!!ignore, { forward: true });
        } catch (e) {}
    }
});

// 打开全部玩家窗口（1440x968）
ipcMain.handle('open-all-players', async () => {
    const win = new BrowserWindow({
        width: 1440,
        height: 968,
        show: true,
        frame: true,
        transparent: false,
        resizable: true,
        webPreferences: { nodeIntegration: true, contextIsolation: false }
    });
    await win.loadFile('all_players.html');
    win.center();
});

// 提供光标位置与窗口位置给渲染进程，实现锁定时仅标题栏可点击
ipcMain.handle('get-cursor-and-window-bounds', () => {
    try {
        const point = screen.getCursorScreenPoint();
        const bounds = mainWindow && !mainWindow.isDestroyed() ? mainWindow.getBounds() : { x: 0, y: 0, width: 0, height: 0 };
        return { point, bounds };
    } catch (e) {
        return { point: { x: -1, y: -1 }, bounds: { x: 0, y: 0, width: 0, height: 0 } };
    }
});

ipcMain.handle('close-app', () => {
    app.quit();
});

ipcMain.handle('minimize-app', () => {
    if (mainWindow) {
        mainWindow.minimize();
    }
});
